<?php
namespace api\modules\v1\controllers;

use common\modules\storage\models\FileStorageItem;
use common\modules\storage\actions\UploadAction;
use common\modules\storage\actions\DeleteAction;
use common\core\base\BaseApiActiveController;
use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * Class FileStorageController.
 */
class FileStorageController extends BaseApiActiveController
{
    public $needLogin = true;
    
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => [
                        'post'
                    ],
                    'upload-delete' => [
                        'delete'
                    ]
                ]
            ]
        ];
    }

    public function actions()
    {
        return [
            'upload' => [
                'class' => UploadAction::className(),
                'deleteRoute' => 'upload-delete'
            ],
            'upload-delete' => [
                'class' => DeleteAction::className()
            ]
        ];
    }

    /**
     * Displays a single FileStorageItem model.
     * 
     * @param integer $id            
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->findModel($id);
    }

    /**
     * Deletes an existing FileStorageItem model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * 
     * @param integer $id            
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);

        $model->delete();

        Yii::$app->getResponse()->setStatusCode(204);
    }

    /**
     * Finds the FileStorageItem model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * 
     * @param integer $id            
     * @return FileStorageItem the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = FileStorageItem::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
